package com.beiding.jsonanalyzer.analyze;

import com.beiding.jsonanalyzer.Analyzer;
import com.beiding.jsonanalyzer.Key;
import com.beiding.jsonanalyzer.analyze.func.FuncFactory;

public class KeyUtils {


    /**
     * 如果exp为字符串
     * 对于
     * '文本' 格式的将自动识别为文本,否则解析为key
     *
     * @param exp
     * @param keyMode
     * @return
     */
    public static Object handleKey(Object exp, KeyMode keyMode) {
        if (exp instanceof FuncFactory) {
            return ((FuncFactory) exp).createInstance();
        }
//        if (keyMode == KeyMode.TEXT_TO_KEY) {
//            if (exp instanceof String) {
//
//                String t = (String) exp;
//
//                t = t.trim();
//                return Key.parse(t);
//            } else if (exp instanceof FuncFactory) {
//                return ((FuncFactory) exp).createInstance();
//            }
//        }
        return exp;
    }

    public static class LastSegmentResult {

        /**
         * 父节点
         */
        private Object parent;

        /**
         * 最后一级key
         */
        private Key lastKey;

        /**
         * 是否是key
         */
        private boolean flagKey;

        private boolean haveParent;


        public LastSegmentResult(boolean flagKey, boolean haveParent, Object parent, Key lastKey) {
            this.flagKey = flagKey;
            this.haveParent = haveParent;
            this.parent = parent;
            this.lastKey = lastKey;
        }

        public Object getParent() {
            return parent;
        }

        public Key getLastKey() {
            return lastKey;
        }

        public boolean isFlagKey() {
            return flagKey;
        }

        public boolean isHaveParent() {
            return haveParent;
        }
    }


    public static LastSegmentResult handleLastSegment(Object holder, Object key) {
        if (!(key instanceof Key)) {
            return new LastSegmentResult(false, false, null, null);
        }
        Key k = (Key) key;

        int segmentLength = k.segmentLength();

        Key subKey = k.subKey(0, segmentLength - 1);

        Object parent = Analyzer.get(holder, subKey, Object.class);

        if (parent == null) {
            return new LastSegmentResult(true, false, null, null);
        }

        //最后一段key
        Key lastKey = k.subKey(segmentLength - 1);

        return new LastSegmentResult(true, true, parent, lastKey);

    }

}
